package com.zndroid.utils.impl;

import android.os.Build;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @name:CryptoUtil
 * @author:lazy
 * @email:luzhenyuxfcy@sina.com
 * @date : 2020/10/21 13.46
 * @version:
 * @description:加解密相关
 */
@SuppressWarnings("unused")
public class CryptoUtil {
    /**
     * get MD5
     * @param originStr string
     * */
    public String getMD5(String originStr, boolean ... toUpperCase) {
        boolean cases = false;
        if (toUpperCase != null && toUpperCase.length > 0) {
            cases = toUpperCase[0];
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            return bytesToHexString(originStr.getBytes(StandardCharsets.UTF_8), cases);
        } else {
            return bytesToHexString(originStr.getBytes(Charset.forName("UTF-8")), cases);
        }
    }

    public String getMD5(File file, boolean ... toUpperCase) {
        boolean cases = false;
        if (toUpperCase != null && toUpperCase.length > 0) {
            cases = toUpperCase[0];
        }

        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest;
        FileInputStream in;
        int maxLen = 1 << 10;
        byte[] buffer = new byte[maxLen];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, maxLen)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bytesToHexString(digest.digest(), cases);
    }

    private String bytesToHexString(byte[] src, boolean toUpperCase) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return toUpperCase ? stringBuilder.toString().toUpperCase() : stringBuilder.toString().toLowerCase();
    }

    /**
     * 加密解密算法 执行一次 加密，再执行一次解密 (可逆加解密算法)
     * @param inStr - 需要加密的字符串
     * @return string
     */
    public String reversibleCrypto(String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        return new String(a);
    }
}
